package com.goldgov.code.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.goldgov.code.service.Project;
import com.goldgov.code.service.ProjectService;
import com.goldgov.code.service.User;
import com.goldgov.route.service.ProjectRouteRule;
import com.goldgov.route.service.RouteRuleService;

@RestController
@RequestMapping("/project")
public class ProjectController {
	
	@Autowired
	private ProjectService projectService;
	
	@Autowired
	private RouteRuleService routeRuleService;

	@PostMapping
	public String addProject(Project project){
		projectService.addProject(project);
		
		return "SUCCESS";
	}
	
	@PutMapping
	public String updateProject(Project project,HttpServletRequest request){
		String[] ruleIDs = request.getParameterValues("ruleID");
		String[] versionIDs = request.getParameterValues("versionID");
		projectService.updateProject(project);
		
		ProjectRouteRule[] rules = new ProjectRouteRule[ruleIDs.length];
		for (int i = 0; i < ruleIDs.length; i++) {
			rules[i] = new ProjectRouteRule(project.getProjectID(),ruleIDs[i],versionIDs[i]);
		}
		routeRuleService.updateProjectRouteRule(project.getProjectID(),rules);
		
		return "SUCCESS";
	}
	
	@GetMapping("/{projectID}")
	public Project getProject(@PathVariable("projectID") String projectID){
		return projectService.getProject(projectID);
	}
	
	@GetMapping
	public List<Project> listProject(HttpServletRequest request){
		User user = (User)request.getSession().getAttribute(User.USER_KEY_NAME);
		List<Project> listProject = projectService.listProject(user.getUserID());
		return listProject;
	}
}
